<?php

namespace app\common\model\mycurrency;

use app\common\model\Config;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

class User extends Model
{

    

    // 表名
    protected $name = 'user';

    /**
     * 生成用户昵称
     */
    public static function getNickname(){
        $user_nickname_prefix = Config::where(['name' => 'user_nickname_prefix'])->value('value');
        $nickname = $user_nickname_prefix . mt_rand(100000, 999999);

        $exists = self::where('nickname', $nickname)->value('id');
        if (!$exists) {
            return $nickname;
        }
        return self::getNickname();
    }



    /**
     * 微信信息解密 - 获取微信手机号
     * @param  string  $appid  小程序id
     * @param  string  $sessionKey 小程序密钥
     * @param  string  $encryptedData 在小程序中获取的encryptedData
     * @param  string  $iv 在小程序中获取的iv
     * @return array 解密后的数组
     */
    public static function decryptData($appid, $sessionKey, $encryptedData, $iv) {
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;
        if (strlen($sessionKey) != 24) {
            //return $IllegalAesKey;
            throw new Exception('sessionKey错误');
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            //return $IllegalIv;
            throw new Exception('iv错误');
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            //return $IllegalBuffer;
            throw new Exception('解析失败');
        }
        if ($dataObj->watermark->appid != $appid) {
            //return $DecodeBase64Error;
            throw new Exception('appid不匹配');
        }
        $data = json_decode($result, true);
        return $data['purePhoneNumber'];
    }


}
